package cn.bugstack.springframework.beans.factory.support;

import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
import cn.bugstack.springframework.beans.factory.config.BeanPostProcessor;
import cn.bugstack.springframework.beans.factory.config.ConfigurableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ouyangzhao
 * @description: BeanDefinition的注册表接口
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {


    private final List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();



    @Override
    public Object getBean(String beanName) throws BeansException {
        return doGetBean(beanName,null);
    }



    @Override
    public Object getBean(String beanName, Object... args) throws BeansException {
        return doGetBean(beanName,args);
    }

    protected <T> T doGetBean(String beanName, Object[] args) throws BeansException {
        Object singleton = getSingleton(beanName);
        if(singleton != null){
            return (T) singleton;
        }
        BeanDefinition beanDefinition = getBeanDefinition(beanName);
        return (T) createBean(beanName,beanDefinition,args);
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    @Override
    public <T> T getBean(String beanName, Class<T> requestedType) throws BeansException {
        return  (T) getBean(beanName);
    }

    



    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor){
        beanPostProcessorList.remove(beanPostProcessor);
        beanPostProcessorList.add(beanPostProcessor);
    }


    abstract Object createBean(String beanName, BeanDefinition beanDefinition,Object [] args) throws BeansException;


    public List<BeanPostProcessor> getBeanPostProcessors(){
        return this.beanPostProcessorList;
    }



}
